package com.zq.solution;

import java.util.Scanner;

/**
 * @ClassName IntegerReverse
 * @Description 整数反转
 * 给出一个 32 位的有符号整数，你需要将这个整数中每位上的数字进行反转。
 * 假设我们的环境只能存储得下 32 位的有符号整数，则其数值范围为 [−231,  231 − 1]。请根据这个假设，如果反转后整数溢出那么就返回 0
 * @Author ZQ
 * @Date 2020/10/9 17:38
 * @Version 1.0
 */
public class IntegerReverse {
    public static int reverse(int x) {
        if (x > Math.pow(2,31) || x < (Math.pow(2,31)-1) * -1)    return 0;
        int result = 0;
        int a = -1;
        if (x > 0) a = 1;
        String str = String.valueOf(Math.abs(x));
        char[] arr = str.toCharArray();

        int length = arr.length;
        if (length % 2 == 1) length = length - 1;
        for (int i = 0; i < length / 2; i++){
            int j = arr.length -1 -i;
            char t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
        String arrStr = String.valueOf(arr);
        long l = Long.parseLong(arrStr);
        if (l < Math.pow(2,31))    result = Integer.parseInt(arrStr) * a ;
        return result;
    }
    public static int reverse1(int x) {
        if (x > Math.pow(2,31) || x < (Math.pow(2,31)-1) * -1)    return 0;
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
    public static void main(String[] args) {
        System.out.println("请输入一个整数：");
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        System.out.println(reverse(a));
        System.out.println(reverse1(a));
    }
}
